#! /usr/bin/python3
# -*- coding: utf-8 -*-

from treebook import TreeBook

class Logger:
    def Info(self, text):
        print text

    def Warning(self, text):
        print text

    def Error(self, text):
        print text

class WordType:
    "Неизвестно"
    UNKNOWN = 0
    "Существительное"
    NOUN = 1
    "Глагол"
    VERB = 2
    "Прилагательное"
    ADJECTIVAL = 3
    "Числительное"
    NUMERAL = 4
    "Местоимения"
    PRONOUN = 5
    "Наречие"
    ADVERB = 6
    "Причастие"
    PARTICIPLE = 7

class Word:
    def __init__(self, word, params = None):
        self.word = word

        if params:
            if isinstance(params, dict):
                if params.has_key("word"):
                    raise Exception("Word param 'word' can not bes set")
                if len(params):
                    self.__dict__.update(params)
            else:
                raise Exception("Word 'params' must be a dictionary")

    def get_param(self, name):
        return self.__dict__.get(name, None)

    def set_param(self, name, value):
        self.__dict__[name] = value

    def __str__(self):
        return "%s" % (self.word)

    def __unicode__(self):
        return "%s" % (self.word)

class WordStack:
    def __init__(self):
        self.stack = []

    def push(self, word, **kwargs):
        #print "Kwargs: %s" % kwargs
        self.stack.append(Word(word, kwargs))

    def pop(self, word):
        return self.stack.pop()

    def get_stack(self):
        return self.stack

class Parser:
    def __init__(self):
        self.word_stack = WordStack()
        self.dictionary = TreeBook()

    def is_word(self, word):
        for c in word:
            if not self.is_letter(ord(c)):
                return False
        return True

    """
    """
    def is_letter(self, code):
        if not isinstance(code, (int, long)):
            raise Exception("Code is not integer")
        return (code >= 1072 and code <= 1103)

    """
    """
    def is_punctuation(self, code):
        if not isinstance(code, (int, long)):
            raise Exception("Code is not integer")
        return (code in [34, 33, 44, 45, 46, 58, 59, 63])

    """
    """
    def is_space(self, code):
        if not isinstance(code, (int, long)):
            raise Exception("Code is not integer")
        return (code in [9, 32, 10, 13])

    """
    Parse text
    """
    def parse(self, text):
        self.make_word_stack(text)

        for word in self.word_stack.get_stack():
            word.set_param("type", self.analyze_word(unicode(word)))

    def debug_print(self):
        #print "Print stack:"
        #for word in self.word_stack.stack:
        #    print unicode(word)#.decode('utf8','cp1251')

        print "Print dictionary:"
        self.dictionary.list()

    def make_word_stack(self, text):
        text = unicode(text)
        word = ""
        for char in text:
            n = ord(char.lower())
            # letter
            if self.is_letter(n):
                word += char
            # punctuation
            elif self.is_punctuation(n):
                self.word_stack.push(word)
                self.word_stack.push(char)
                word = ""
                # TODO: skip next space
            # spaces
            elif self.is_space(n):
                if n != 13: # skip #13
                    self.word_stack.push(word)
                    self.word_stack.push(" ")
                    word = ""
            #skip
            else:
                Logger().Warning("Unknown char '%s'(%d)" % (char, ord(char)))

    def pop_word_stack(self):
        pass

    """
    Define the word type
    """
    def analyze_word(self, word):
        length = len(word)

        if length and length <= 55 and self.is_word(word):
            node = self.dictionary.find(word)
            if node.data != None:
                pass
            else:
                node.data = Word(word)

    def is_vowel(self, letter):
        vowel = "aеёиоуыэюя"
        if letter in vowel:
            return True
        return False

    def get_end(self, node):
        length = len(word)



text = u"""
лол
"""

test = Parser()
test.dictionary.load_from_file("dict.wt")
test.parse(text)
test.debug_print()
test.dictionary.save_to_file("dict.wt")